﻿Imports MICROFORMA.BEL
Imports MICROFORMA.DIL
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports System.Data.Common

Public Class TypeDocDA
    Implements DIL.TypeDocDI

    Public Function ListAll() As System.Data.DataTable Implements DIL.TypeDocDI.ListAll

        Dim db As Database = DatabaseFactory.CreateDatabase()
        Dim query As String = "select * from TipoDocumental   Order By Nombre" 'TODO: HardCode

        Dim dbCommand As DbCommand = db.GetSqlStringCommand(query)

        Dim TypeDocDataSet As DataSet = Nothing

        TypeDocDataSet = db.ExecuteDataSet(dbCommand)

        Return TypeDocDataSet.Tables(0)

    End Function

    Public Function ListItem(ByVal idTypeDoc As Short) As DataTable Implements DIL.TypeDocDI.ListItem

        Dim db As Database = DatabaseFactory.CreateDatabase()
        Dim query As String = "select * from TipoDocumental where IdPlantilla=" & idTypeDoc & " Order By Nombre" 'TODO: HardCode
        Dim dbCommand As DbCommand = db.GetSqlStringCommand(query)

        Dim TypeDocDataSet As DataSet = Nothing

        TypeDocDataSet = db.ExecuteDataSet(dbCommand)

        Return TypeDocDataSet.Tables(0)

    End Function

    Public Function Add(ByVal TypeDocBE As BEL.TypeDocBE) As String Implements DIL.TypeDocDI.Add
        Dim db As Database = DatabaseFactory.CreateDatabase()

        Try
            Dim cmd As DbCommand

            'Crea la tabla en la base de datos
            Dim query As String = "Create table " & TypeDocBE.Nombre.Trim.Replace(" ", "") _
                & " (IdDocumento int NOT NULL PRIMARY KEY)"

            cmd = db.GetSqlStringCommand(query)
            cmd.CommandType = CommandType.Text
            db.ExecuteNonQuery(cmd)


            query = "Insert into TipoDocumental (Nombre,Descripcion)" _
                                    & "Values ('" & TypeDocBE.Nombre & "','" & TypeDocBE.Descripcion & "')"

            cmd = db.GetSqlStringCommand(query)
            db.ExecuteNonQuery(cmd)


            Return "OK"

        Catch ex As Exception

            Return ex.Message.ToString

        End Try
    End Function

    Public Function Update(ByVal typeDocBE As TypeDocBE) As String Implements DIL.TypeDocDI.Update
        Dim db As Database = DatabaseFactory.CreateDatabase()
        Dim query As String
        Try

            query = "update tipodocumental set Descripcion='" & typeDocBE.Descripcion _
                    & "', habilitado='" & typeDocBE.Habilitado & "' where idPlantilla=" & typeDocBE.IdTypeDoc
            db.ExecuteNonQuery(CommandType.Text, query)
            Return "OK"
        Catch ex As Exception
            Return ex.Message.ToString
        End Try
    End Function

End Class

